package com.learnjava.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.learnjava.bean.Info;
import com.learnjava.service.InfoService;
import com.learnjava.service.impl.InfoServiceImpl;

import net.sf.json.JSONObject;

/**
 * @Description:
 * @Author: xiangty
 * @Date: 2018-03-30
 */
@SuppressWarnings("serial")
public class InfoAction extends HttpServlet {

    //调用业务层
    private InfoService infoService = new InfoServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //编码格式,防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String action = request.getParameter("action");

        if("all".equals(action)){
            List<Info> infoList=infoService.getAll();
            request.setAttribute("infoList", infoList);
            request.getRequestDispatcher("/page/list.jsp").forward(request, response);
        }

        if("yanzheng".equals(action)){
            String username = request.getParameter("username");

            List<Info> infoList = infoService.getInfoByUsername(username);

            Map<String, Object> params = new HashMap<>();
            if(infoList != null && !infoList.isEmpty()){
                params.put("flag",true);
                params.put("message","用户名已经存在");
            } else {
                params.put("flag",false);
                params.put("message","用户名符合条件");
            }
            JSONObject jsonObject = JSONObject.fromObject(params);

            response.getWriter().print(jsonObject);
            response.getWriter().flush();
            response.getWriter().close();
        }

        if("add".equals(action)){
            Info info = new Info();
            info.setUsername(request.getParameter("username"));
            info.setPassword(request.getParameter("password"));
            infoService.addInfo(info);

            // 页面回显
            List<Info> infoList=infoService.getAll();
            request.setAttribute("infoList", infoList);
            request.getRequestDispatcher("/page/list.jsp").forward(request, response);
        }

    }


}
